#include "Sphere.h"

Sphere::Sphere()
{
	position = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
	radius = 1.0f;
	colour = Colour(1.0f, 0.0f, 0.0f, 1.0f);
}

Sphere::Sphere(const D3DXVECTOR3& pos, float rad, const Colour& col)
{
	position = pos;
	radius = rad;
	colour = col;
}

const D3DXVECTOR3& Sphere::GetNormalAt(const D3DXVECTOR3& coord)
{
	D3DXVECTOR3 normal = coord - position;
	D3DXVec3Normalize(&normal, &normal);
	return normal;
}

float Sphere::FindIntersection(const Ray& ray)
{
	D3DXVECTOR3 rayOrig = ray.GetOrigin();
	D3DXVECTOR3 rayDir = ray.GetDirection();
	
	//float a = 1.0f;
	float b = (2.0f * (rayOrig.x - position.x) * rayDir.x) +
			(2.0f * (rayOrig.y - position.y) * rayDir.y) +
			(2.0f * (rayOrig.z - position.z) * rayDir.z);

	float c = (pow(rayOrig.x - position.x, 2.0f) +
			pow(rayOrig.y - position.y, 2.0f) +
			pow(rayOrig.z - position.z, 2.0f)) -
			(radius * radius);

	float discrimanant = b * b - 4.0f * c;

	if (discrimanant > 0.0f)
	{
		// intersected
		// test which side ray collided
			// side closest to camera

		float root1 = (((-1.0f * b) - sqrtf(discrimanant)) / 2.0f) - 0.000001f; // arbitary 0.000001f val

		if (root1 > 0.0f)
		{
			// the first root is the smallest positive root
			return root1;
		}
		else
		{
			// the second root is the smnallest positive root
			float root2 = ((sqrtf(discrimanant) - b) / 2.0f) - 0.000001f;
			return root2;
		}
	}
	else
	{
		// no collision
		return -1.0f;
	}
}